package com.example.checkqufuface.View.QufuFaceProject;

import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.checkqufuface.Base.BaseActivity;
import com.example.baselibrary.Utils.Customer;
import com.example.baselibrary.Utils.LogUtil;
import com.example.baselibrary.Utils.SPUtils;
import com.example.checkqufuface.Utils.SelfToastUtil;
import com.example.baselibrary.Utils.StringUtil;
import com.example.baselibrary.Utils.TimeUtil;
import com.example.checkqufuface.Customer.BottomTicketSearchDialog;
import com.example.checkqufuface.Customer.CustomChangePwWindow;
import com.example.checkqufuface.Customer.CustomFreeInWindow;
import com.example.checkqufuface.Customer.CustomImformationWindow;
import com.example.checkqufuface.Customer.CustomSettingBindWindow;
import com.example.checkqufuface.R;
import com.example.checkqufuface.RetrufitHelp.BaseSubscriber;
import com.example.checkqufuface.RetrufitHelp.ExceptionHandle;
import com.example.checkqufuface.RetrufitHelp.RetrofitClient;
import com.example.checkqufuface.Server.RefreshTokenService;
import com.example.checkqufuface.bean.QufuAddOrRelieveTerminalBindRequsetBean;
import com.example.checkqufuface.bean.QufuAddOrRelieveTerminalBindResultBean;
import com.example.checkqufuface.bean.QufuByComputerCpuIdRequsetBean;
import com.example.checkqufuface.bean.QufuByComputerCpuIdResultBean;
import com.example.checkqufuface.bean.QufuUpdateUserPassWordRequsetBean;
import com.example.checkqufuface.bean.QufuUpdateUserPassWordResultBean;
import com.example.checkqufuface.bean.QufufTerminalTypeListRequestBean;
import com.example.checkqufuface.bean.QufufTerminalTypeListResultBean;
import com.example.checkqufuface.bean.QufufindCertificateTypeRequestBean;
import com.example.checkqufuface.bean.QufufindCertificateTypeResultBean;
import com.example.checkqufuface.bean.QufufindFreeCardProductSelectResultBean;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.core.utils.LogHelper;
import com.zkteco.android.biometric.module.idcard.IDCardReader;
import com.zkteco.android.biometric.module.idcard.IDCardReaderExceptionListener;
import com.zkteco.android.biometric.module.idcard.IDCardReaderFactory;
import com.zkteco.android.biometric.module.idcard.exception.IDCardReaderException;
import com.zkteco.android.biometric.module.idcard.meta.IDCardInfo;
import com.zkteco.android.biometric.module.idcard.meta.IDPRPCardInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class QufuMainActivity extends BaseActivity {

    private TextView setting;
    private TextView changePw;
    private LinearLayout freeIn;
    private LinearLayout facePick;
    private LinearLayout tickSearch;
    private CustomChangePwWindow changePwWindow;
    private CustomSettingBindWindow settingWindow;
    private CustomFreeInWindow freeWindow;
    private CustomImformationWindow ImformationWindow;
    private QufufTerminalTypeListRequestBean listRequestBean;
    private List<QufufTerminalTypeListResultBean.DataBean> bindData;
    private List<String> bingIdStr;
    private QufuAddOrRelieveTerminalBindRequsetBean bindRequsetBean;
    private QufuUpdateUserPassWordRequsetBean userPassWordRequsetBean;
    private List<QufufindFreeCardProductSelectResultBean.DataBean> freeData;
    private QufuByComputerCpuIdRequsetBean byComputerCpuIdRequsetBean;
    private boolean IDopen = false;
    private static Runnable runnableID;
    private static final int PROCESSOR_IDCODE = 20;

    private QufufindCertificateTypeRequestBean typeRequestBean;
    private List<QufufindCertificateTypeResultBean.DataBean> typeData;
    private static EditText imforName;
    private Intent intent;
    private String scenicTicketId;
    private boolean freeClick = false;

    private long timeNew;
    private long timeOld;
    private String OldID;

    // 曲阜 中身份证识别 新的集成

    private static final int VID = 1024;    //IDR VID
    private static final int PID = 50010;     //IDR PID
    private IDCardReader idCardReader = null;
    private boolean bopen = false;
    private boolean bStoped = false;
    private int mReadCount = 0;
    private CountDownLatch countdownLatch = null;

    private Context mContext = null;
    private UsbManager musbManager = null;
    private final String ACTION_USB_PERMISSION = "com.example.scarx.idcardreader.USB_PERMISSION";

    private BottomTicketSearchDialog bottomTicketSearchDialog;

    private boolean isFreeFacePick;
    private boolean isFacePick;
    private boolean isTickeSearch;

    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        try {
                            OpenDevice();
                        } catch (Exception e) {

                        }
                    } else {
                        Toast.makeText(mContext, "USB未授权", Toast.LENGTH_SHORT).show();
                        //mTxtReport.setText("USB未授权");
                    }
                }
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getView() {
        return R.layout.activity_qufu_main;
    }

    @Override
    public void init() {

        mContext = this;
        activityBase = this;

        if (bingIdStr == null) {
            bingIdStr = new ArrayList<>();
        }

        if (freeData == null) {
            freeData = new ArrayList<>();
        }

        if (listRequestBean == null) {
            listRequestBean = new QufufTerminalTypeListRequestBean();
        }

        //绑定的对象
        if (bindRequsetBean == null) {
            bindRequsetBean = new QufuAddOrRelieveTerminalBindRequsetBean();
        }

        // 修改密码对象
        if (userPassWordRequsetBean == null) {
            userPassWordRequsetBean = new QufuUpdateUserPassWordRequsetBean();
        }

        if (byComputerCpuIdRequsetBean == null) {
            byComputerCpuIdRequsetBean = new QufuByComputerCpuIdRequsetBean();
        }

        if (typeRequestBean == null) {
            typeRequestBean = new QufufindCertificateTypeRequestBean();
        }

        if (typeData == null) {
            typeData = new ArrayList<>();
        }

        setting = findViewById(R.id.tv_qufumain_setting);
        changePw = findViewById(R.id.tv_qufumain_change_pw);


        freeIn = findViewById(R.id.ll_free_in);
        facePick = findViewById(R.id.ll_face_pick);
        tickSearch = findViewById(R.id.ll_ticket_search);

        initData();
        // 获取绑定终端列表
        findTerminalNameAndIdByTerminalTypeList();

        //查询免费票产品
        findFreeCardProductSelect();

        //查询证件类型
        findCertificateTypeSelectList();

        // 启动服务， 去更新 token
        startService(new Intent(QufuMainActivity.this, RefreshTokenService.class));

        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        mContext.registerReceiver(mUsbReceiver, filter);
        //开启身份证读卡器
        if (bopen) {
            return;
        }
        RequestDevicePermission();

    }

    private void findCertificateTypeSelectList() {
        DialogTipShow("请稍等。。。");
        RetrofitClient.getInstance(QufuMainActivity.this, BASE_URL, headers).findCertificateTypeSelectList(typeRequestBean, new BaseSubscriber<QufufindCertificateTypeResultBean>(QufuMainActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                DiglogTipDiss();
                SelfToastUtil.getInstance().show(e.message);

            }

            @Override
            public void onNext(QufufindCertificateTypeResultBean qufuByComputerCpuIdResultBean) {
                DiglogTipDiss();
                String code = qufuByComputerCpuIdResultBean.getCode();
                typeData.clear();
                if (code.equals("200")) {
                    typeData.addAll(qufuByComputerCpuIdResultBean.getData());
                } else {
                    SelfToastUtil.getInstance().show(qufuByComputerCpuIdResultBean.getMessage());
                }
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
    }


    // 返回 true  相同 小于  30 秒  那么就 不处理
    private boolean checkIDAgain(String m_strIDCards) {
        if (m_strIDCards.equals(OldID) && timeNew - timeOld < 1000 * 10) {
            System.out.println("zyf  未超过30秒 拒绝访问" + TimeUtil.getLocationTime());
            return true;
        } else {
            System.out.println("zyf  超过30秒 去访问" + TimeUtil.getLocationTime());
            timeOld = timeNew;
            OldID = m_strIDCards;
            return false;
        }
    }


    private void findFreeCardProductSelect() {
        RetrofitClient.getInstance(QufuMainActivity.this, BASE_URL, headers).findFreeCardProductSelect(new BaseSubscriber<QufufindFreeCardProductSelectResultBean>(QufuMainActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                SelfToastUtil.getInstance().show(e.message);
            }

            @Override
            public void onNext(QufufindFreeCardProductSelectResultBean qufuUpdateUserPassWordResultBean) {
                String code = qufuUpdateUserPassWordResultBean.getCode();
                freeData.clear();
                if (code.equals("200")) {
                    freeData.addAll(qufuUpdateUserPassWordResultBean.getData());
                } else {
                    SelfToastUtil.getInstance().show(qufuUpdateUserPassWordResultBean.getMessage());
                }
            }
        });
    }

    private void findTerminalNameAndIdByTerminalTypeList() {

        listRequestBean.setTerminalTypeStr("8");
        RetrofitClient.getInstance(QufuMainActivity.this, BASE_URL, headers).findTerminalNameAndIdByTerminalTypeList(listRequestBean, new BaseSubscriber<QufufTerminalTypeListResultBean>(QufuMainActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                SelfToastUtil.getInstance().show(e.message);
            }

            @Override
            public void onNext(QufufTerminalTypeListResultBean qufufTerminalTypeListResultBean) {
                String code = qufufTerminalTypeListResultBean.getCode();
                if (code.equals("200")) {
                    bindData = qufufTerminalTypeListResultBean.getData();
                    for (int i = 0; i < bindData.size(); i++) {
                        bingIdStr.add(bindData.get(i).getTerminalShortName());
                    }
                } else {
                    SelfToastUtil.getInstance().show(qufufTerminalTypeListResultBean.getMessage());
                }
            }
        });

    }

    private void initData() {

        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToBind();

            }
        });

        changePw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoChangePw();
            }
        });

        //点击免费入园
        freeIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                isFreeFacePick = true;
                isFacePick = false;
                isTickeSearch = false;

                //免费入园前 先绑定终端
                if (StringUtil.isNullOrEmpty((String) SPUtils.get(QufuMainActivity.this, Customer.QUFU_TERMINALID, ""))) {
                    SelfToastUtil.getInstance().show("请先点击右上角设置进行终端绑定");
                    return;
                }

                if (freeData == null || freeData.size() <= 0) {
                    SelfToastUtil.getInstance().show("免费票种为空,无法生成免费票");
                } else {
                    freeInShow(freeData);
                }

            }
        });


        // 人脸信息采集
        facePick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //免费入园前 先绑定终端
                if (StringUtil.isNullOrEmpty((String) SPUtils.get(QufuMainActivity.this, Customer.QUFU_TERMINALID, ""))) {
                    SelfToastUtil.getInstance().show("请先点击右上角设置进行终端绑定");
                    return;
                }

                isFreeFacePick = false;
                isFacePick = true;
                isTickeSearch = false;
                //点击人脸信息采集，那么就要吧免费票数据放空
                scenicTicketId = null;

                startActivity(new Intent(QufuMainActivity.this,FacePickActivity.class));

//                SelfToastUtil.getInstance().show("该功能暂时无法为您服务，请包涵");

            }
        });

        //票查询
        tickSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                isFreeFacePick = false;
                isFacePick = false;
                isTickeSearch = true;

                bottomTicketSearchDialog = null;
                if (bottomTicketSearchDialog == null) {
                    bottomTicketSearchDialog = new BottomTicketSearchDialog(QufuMainActivity.this, BASE_URL, headers, "");
                }
                bottomTicketSearchDialog.show();

            }
        });
    }

    private void freeInShow(final List<QufufindFreeCardProductSelectResultBean.DataBean> freeData) {

        freeWindow = new CustomFreeInWindow(QufuMainActivity.this, freeData);

        freeWindow.setGridItemListener(new CustomFreeInWindow.GridItemListener() {
            @Override
            public void GridItem(int pos) {
                //点击跳转，到信息输入界面  隐藏界面，显示下一个界面
                scenicTicketId = freeData.get(pos).getScenicTicketId() + "";
                informationShow("", "", "");
                freeClick = true;
                freeWindow.dismiss();
            }
        });

        freeWindow.showAtLocation(freeIn, Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, 0);
        freeWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                freeWindow.backgroundAlpha(QufuMainActivity.this, 1f);
            }
        });

    }

    //身份信息输入界面
    private void informationShow(String name, String sex, String IDNumber) {

        if (ImformationWindow != null) {
            ImformationWindow.dismiss();
            ImformationWindow = null;
        }

        if (ImformationWindow == null) {
            ImformationWindow = new CustomImformationWindow(QufuMainActivity.this, typeData, name, sex, IDNumber);
        }
        ImformationWindow.setQuerenTvListener(new CustomImformationWindow.QuerenTvListener() {
            @Override
            public void querenTv(String name, String sex, String type, String number, String phone) {
                //点击了确定，就跳转到下一个界面进行 人脸采集
                if (StringUtil.isNullOrEmpty(name)) {
                    SelfToastUtil.getInstance().show("姓名输入为空，请检查");
                    return;
                }

                if (StringUtil.isNullOrEmpty(type)) {
                    SelfToastUtil.getInstance().show("证件类型输入为空，请检查");
                    return;
                }
                if (StringUtil.isNullOrEmpty(number)) {
                    SelfToastUtil.getInstance().show("证件号码输入为空，请检查");
                    return;
                }

                intent = new Intent(QufuMainActivity.this, FaceSaveActivity.class);
                intent.putExtra("name", name);
                intent.putExtra("sex", sex);
                intent.putExtra("type", type);
                intent.putExtra("number", number);
                intent.putExtra("phone", phone);
                intent.putExtra("scenicTicketId", scenicTicketId);
                startActivity(intent);
                ImformationWindow.dismiss();
                freeClick = false;
                SPUtils.put(QufuMainActivity.this, Customer.QUFU_IMFOR_NAME, "");
                SPUtils.put(QufuMainActivity.this, Customer.QUFU_IMFOR_SXE, "");
                SPUtils.put(QufuMainActivity.this, Customer.QUFU_IMFOR_TYPE, "");
                SPUtils.put(QufuMainActivity.this, Customer.QUFU_IMFOR_ID, "");
            }
        });

        ImformationWindow.setQuXiaoTvListener(new CustomImformationWindow.QuXiaoTvListener() {
            @Override
            public void quXiaoTv() {
                freeClick = false;
            }
        });

        try {
            ImformationWindow.showAtLocation(freeIn, Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, 0);
            ImformationWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    freeClick = false;
                    ImformationWindow.backgroundAlpha(QufuMainActivity.this, 1f);
                }
            });
        } catch (Exception e) {

        }
    }

    private void goToBind() {

        if (bingIdStr != null && bingIdStr.size() <= 0) {
            SelfToastUtil.getInstance().show("终端列表为空，请先确认数据，如果数据更新，请重新登入尝试");
            return;
        }

        settingWindow = new CustomSettingBindWindow(QufuMainActivity.this, bingIdStr, new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SelfToastUtil.getInstance().show(bingIdStr.get(position));
            }
        });

        settingWindow.setQuerenTvListener(new CustomSettingBindWindow.QuerenTvListener() {
            @Override
            public void querenTv(String id, int pos) {
                // 点击确定 就要去干活了
                if (StringUtil.isNullOrEmpty(id)) {
                    SelfToastUtil.getInstance().show("请选择绑定id");
                    return;
                } else {
                    //  有数据那么就去绑定了
                    QufufTerminalTypeListResultBean.DataBean dataBean = bindData.get(pos);
                    addOrRelieveTerminalBind(dataBean, "0");
                }
            }
        });

        settingWindow.setQuXiaoTvListener(new CustomSettingBindWindow.QuXiaoTvListener() {
            @Override
            public void quXiaoTv() {
                // 取消之前如果不知道设备id，那么就要去查询 点击了取消，去做取消操作
                if (StringUtil.isNullOrEmpty((String) SPUtils.get(QufuMainActivity.this, Customer.QUFU_TERMINALID, ""))) {
                    // 如果为空 ，那么就先去请求，然后解绑
                    findTerminalInfoByComputerCpuId();
                    return;
                }

                addOrRelieveTerminalBind(new QufufTerminalTypeListResultBean.DataBean(), "1");
            }
        });
        settingWindow.showAtLocation(setting, Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, 0);
        settingWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                settingWindow.backgroundAlpha(QufuMainActivity.this, 1f);
            }
        });

    }

    private void findTerminalInfoByComputerCpuId() {
        byComputerCpuIdRequsetBean.setTerminalComputerCpuId((String) SPUtils.get(QufuMainActivity.this, Customer.QUFU_DEVICE_ID, ""));
        RetrofitClient.getInstance(QufuMainActivity.this, BASE_URL, headers).findTerminalInfoByComputerCpuId(byComputerCpuIdRequsetBean, new BaseSubscriber<QufuByComputerCpuIdResultBean>(QufuMainActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                SelfToastUtil.getInstance().show(e.message);
            }

            @Override
            public void onNext(QufuByComputerCpuIdResultBean qufuByComputerCpuIdResultBean) {
                String code = qufuByComputerCpuIdResultBean.getCode();
                if (code.equals("200")) {
                    SPUtils.put(QufuMainActivity.this, Customer.QUFU_TERMINALID, qufuByComputerCpuIdResultBean.getData().get(0).getTerminalId() + "");
                    // 获取到数据了，然后再去删除
                    addOrRelieveTerminalBind(new QufufTerminalTypeListResultBean.DataBean(), "1");
                } else {
                    SelfToastUtil.getInstance().show(qufuByComputerCpuIdResultBean.getMessage());
                }
            }
        });
    }

    private void addOrRelieveTerminalBind(final QufufTerminalTypeListResultBean.DataBean terminalId, final String type) {

        if (type.equals("0")) {
            bindRequsetBean.setTerminalId(terminalId.getTerminalId() + "");
        } else {
            bindRequsetBean.setTerminalId((String) SPUtils.get(QufuMainActivity.this, Customer.QUFU_TERMINALID, ""));
        }

        bindRequsetBean.setTerminalSetFlag(type);
        bindRequsetBean.setTerminalComputerCpuId((String) SPUtils.get(QufuMainActivity.this, Customer.QUFU_DEVICE_ID, "") + "");
        bindRequsetBean.setTerminalComputerName("立式人脸采集");
        RetrofitClient.getInstance(QufuMainActivity.this, BASE_URL, headers).addOrRelieveTerminalBind(bindRequsetBean, new BaseSubscriber<QufuAddOrRelieveTerminalBindResultBean>(QufuMainActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                SelfToastUtil.getInstance().show(e.message);
            }

            @Override
            public void onNext(QufuAddOrRelieveTerminalBindResultBean qufuAddOrRelieveTerminalBindResultBean) {
                String code = qufuAddOrRelieveTerminalBindResultBean.getCode();
                if (code.equals("200")) {
                    SelfToastUtil.getInstance().show(qufuAddOrRelieveTerminalBindResultBean.getMessage());
                    if (type.equals("0")) {
                        //如果类型是0 ，就保存
                        SelfToastUtil.getInstance().show("绑定成功");
                        SPUtils.put(QufuMainActivity.this, Customer.QUFU_TERMINALID, terminalId.getTerminalId() + "");
                        SPUtils.put(QufuMainActivity.this, Customer.QUFU_TERMINALNAME, terminalId.getTerminalShortName());
                    } else {
                        SPUtils.put(QufuMainActivity.this, Customer.QUFU_TERMINALID, "");
                        SPUtils.put(QufuMainActivity.this, Customer.QUFU_TERMINALNAME, "");
                        SelfToastUtil.getInstance().show("取消绑定成功");
                    }
                    if (settingWindow != null) {
                        settingWindow.dismiss();
                    }
                } else {
                    SelfToastUtil.getInstance().show(qufuAddOrRelieveTerminalBindResultBean.getMessage());
                }
            }
        });

    }

    private void gotoChangePw() {
        changePwWindow = new CustomChangePwWindow(QufuMainActivity.this);

        changePwWindow.showAtLocation(changePw, Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, 0);
        changePwWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                changePwWindow.backgroundAlpha(QufuMainActivity.this, 1f);
            }
        });

        changePwWindow.setquerenListener(new CustomChangePwWindow.QuerenListener() {
            @Override
            public void querenClick(String yuan, String xin, String que) {
                // 点击确认，后的操作
                String pw = (String) SPUtils.get(QufuMainActivity.this, Customer.QUFU_LOGIN_PASSWORD, "");
                if (!yuan.equals(pw)) {
                    SelfToastUtil.getInstance().show("您输入的原密码，和账户密码不一致，请重新输入");
                    return;
                }
                if (!xin.equals(que)) {
                    SelfToastUtil.getInstance().show("您输入的新密码，和确认密码不一致，请重新输入");
                    return;
                }
                if (xin.equals(yuan)) {
                    SelfToastUtil.getInstance().show("您输入的新密码，和原密码相同，请重新输入");
                    return;
                }

                // 密码校验完毕，可以发起请求进行 更改密码
                GotoChangePw(yuan, xin);

            }
        });
    }

    private void GotoChangePw(String yuan, final String xin) {
        userPassWordRequsetBean.setPassword(yuan);
        userPassWordRequsetBean.setNewPassword(xin);
        RetrofitClient.getInstance(QufuMainActivity.this, BASE_URL, headers).updateUserPassWord(userPassWordRequsetBean, new BaseSubscriber<QufuUpdateUserPassWordResultBean>(QufuMainActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                SelfToastUtil.getInstance().show(e.message);
            }

            @Override
            public void onNext(QufuUpdateUserPassWordResultBean qufuUpdateUserPassWordResultBean) {
                String code = qufuUpdateUserPassWordResultBean.getCode();
                if (code.equals("200")) {
                    SPUtils.put(QufuMainActivity.this, Customer.QUFU_LOGIN_PASSWORD, xin);
                    SelfToastUtil.getInstance().show(qufuUpdateUserPassWordResultBean.getMessage());

                    //由于修改密码所以要跳出去
                    startActivity(new Intent(QufuMainActivity.this, LoginActivity.class));
                    SPUtils.put(QufuMainActivity.this, Customer.QUFU_LOGIN_PASSWORD, "");
                    SPUtils.put(QufuMainActivity.this, Customer.QUFU_IS_REMBER, false);
                    finish();
                } else {
                    SelfToastUtil.getInstance().show(qufuUpdateUserPassWordResultBean.getMessage());
                }
            }
        });
    }

    public void OpenDevice() {
        if (bopen) {
            SelfToastUtil.getInstance().show("设备已连接");
            return;
        }
        try {
            startIDCardReader();
            IDCardReaderExceptionListener listener = new IDCardReaderExceptionListener() {
                @Override
                public void OnException() {
                    //出现异常，关闭设备
                    CloseDevice();
                    //当前线程为工作线程，若需操作界面，请在UI线程处理
                    runOnUiThread(new Runnable() {
                        public void run() {
                            SelfToastUtil.getInstance().show("设备发生异常，断开连接！");
                        }
                    });
                }
            };
            idCardReader.open(0);
            idCardReader.setIdCardReaderExceptionListener(listener);
            bStoped = false;
            mReadCount = 0;
            writeLogToFile("连接设备成功");
            SelfToastUtil.getInstance().show("连接成功");
            bopen = true;
            countdownLatch = new CountDownLatch(1);
            new Thread(new Runnable() {
                public void run() {
                    while (!bStoped) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        boolean ret = false;
                        final long nTickstart = System.currentTimeMillis();
                        try {
                            idCardReader.findCard(0);
                            idCardReader.selectCard(0);
                        } catch (Exception e) {  //IDCardReaderException
                            //continue;
                        }
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        int retType = 0;
                        try {
                            retType = idCardReader.readCardEx(0, 0);
                        } catch (IDCardReaderException e) {
                            writeLogToFile("读卡失败，错误信息：" + e.getMessage());
                        } catch (Exception e) {

                        }
                        if (retType == 1 || retType == 2 || retType == 3) {
                            final long nTickUsed = (System.currentTimeMillis() - nTickstart);
                            final int final_retType = retType;
                            writeLogToFile("读卡成功：" + (++mReadCount) + "次" + "，耗时：" + nTickUsed + "毫秒");
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    if (final_retType == 1) {
                                        LogUtil.d(TimeUtil.getLocationTime());
                                        final IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
                                        //姓名adb
                                        final String strName = idCardInfo.getName();
                                        //民族
                                        String strNation = idCardInfo.getNation();
                                        //出生日期
                                        String strBorn = idCardInfo.getBirth();
                                        //住址
                                        String strAddr = idCardInfo.getAddress();
                                        //身份证号
                                        final String strID = idCardInfo.getId();
                                        //有效期限
                                        String strEffext = idCardInfo.getValidityTime();

                                        final String Sex = idCardInfo.getSex();


                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (freeClick) {
                                                    timeNew = TimeUtil.getLocationTimeLong();
                                                    if (!checkIDAgain(strID)) {
                                                        informationShow(strName, Sex, strID);
                                                    }
                                                }

                                                //如果点击了人脸采集信息
//                                                if (isFacePick) {
//                                                    // 那就去显示票查询页面
//                                                    if (!checkIDAgain(strID)) {
//                                                        timeNew = TimeUtil.getLocationTimeLong();
//                                                        if (!checkIDAgain(strID)) {
//                                                            informationShow(strName, Sex, strID);
//                                                        }
//                                                    }
//                                                }

                                                //如果点击了票查询
                                                if (isTickeSearch) {
                                                    timeNew = TimeUtil.getLocationTimeLong();
                                                    // 那就去显示票查询页面
                                                    if (!checkIDAgain(strID)) {
                                                        bottomTicketSearchDialog.dismiss();
                                                        bottomTicketSearchDialog = null;
                                                        if (bottomTicketSearchDialog == null) {
                                                            bottomTicketSearchDialog = new BottomTicketSearchDialog(QufuMainActivity.this, BASE_URL, headers, strID);
                                                        }
                                                        bottomTicketSearchDialog.show();
                                                    }
                                                }
                                            }
                                        });

                                    } else if (final_retType == 2) {
                                        LogUtil.d(TimeUtil.getLocationTime());
                                        final IDPRPCardInfo idprpCardInfo = idCardReader.getLastPRPIDCardInfo();
                                        //中文名
                                        String strCnName = idprpCardInfo.getCnName();
                                        //英文名
                                        String strEnName = idprpCardInfo.getEnName();
                                        //国家/国家地区代码
                                        String strCountry = idprpCardInfo.getCountry() + "/" + idprpCardInfo.getCountryCode();//国家/国家地区代码
                                        //出生日期
                                        String strBorn = idprpCardInfo.getBirth();
                                        //身份证号
                                        String strID = idprpCardInfo.getId();
                                        //有效期限
                                        String strEffext = idprpCardInfo.getValidityTime();


                                    } else {
                                        LogUtil.d(TimeUtil.getLocationTime());
                                        final IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
                                        //姓名
                                        String strName = idCardInfo.getName();
                                        //民族,港澳台不支持该项
                                        String strNation = "";
                                        //出生日期
                                        String strBorn = idCardInfo.getBirth();
                                        //住址
                                        String strAddr = idCardInfo.getAddress();
                                        //身份证号
                                        String strID = idCardInfo.getId();
                                        //有效期限
                                        String strEffext = idCardInfo.getValidityTime();
                                        //签发机关
                                        String strIssueAt = idCardInfo.getDepart();
                                        //通行证号
                                        String strPassNum = idCardInfo.getPassNum();
                                        //签证次数
                                        int visaTimes = idCardInfo.getVisaTimes();


                                    }
                                }
                            });
                        }
                    }
                    countdownLatch.countDown();
                }
            }).start();
        } catch (IDCardReaderException e) {
            SelfToastUtil.getInstance().show("连接设备失败");
        }
    }

    private void startIDCardReader() {
        if (null != idCardReader) {
            IDCardReaderFactory.destroy(idCardReader);
            idCardReader = null;
        }
        // Define output log level
        LogHelper.setLevel(Log.VERBOSE);
        // Start fingerprint sensor
        Map idrparams = new HashMap();
        idrparams.put(ParameterHelper.PARAM_KEY_VID, VID);
        idrparams.put(ParameterHelper.PARAM_KEY_PID, PID);
        idCardReader = IDCardReaderFactory.createIDCardReader(this, TransportType.USB, idrparams);
    }

    public static void writeLogToFile(String log) {
        try {
            File dirFile = new File("/sdcard/zkteco/");  //目录转化成文件夹
            if (!dirFile.exists()) {              //如果不存在，那就建立这个文件夹
                dirFile.mkdirs();
            }
            String path = "/sdcard/zkteco/idrlog.txt";
            File file = new File(path);
            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            FileOutputStream outStream = new FileOutputStream(file, true);
            log += "\r\n";
            outStream.write(log.getBytes());
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void CloseDevice() {
        if (!bopen) {
            return;
        }
        bStoped = true;
        mReadCount = 0;
        if (null != countdownLatch) {
            try {
                countdownLatch.await(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            idCardReader.close(0);
        } catch (IDCardReaderException e) {
            e.printStackTrace();
        }
        bopen = false;
    }

    private void RequestDevicePermission() {
        musbManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);

        for (UsbDevice device : musbManager.getDeviceList().values()) {
            if (device.getVendorId() == VID && device.getProductId() == PID) {
                Intent intent = new Intent(ACTION_USB_PERMISSION);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
                musbManager.requestPermission(device, pendingIntent);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        IDCardReaderFactory.destroy(idCardReader);
        mContext.unregisterReceiver(mUsbReceiver);
    }
}
